package com.kkd.kkdapp.activity;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.kkd.kkdapp.BaseApplication;
import com.kkd.kkdapp.R;
import com.kkd.kkdapp.adapter.ImagePublishAdapter;
import com.kkd.kkdapp.base.BaseActivity;
import com.kkd.kkdapp.model.ImageItem;
import com.kkd.kkdapp.utils.AppUtil.onToastDismiss;
import com.kkd.kkdapp.utils.AppUtil;
import com.kkd.kkdapp.utils.CustomConstants;
import com.kkd.kkdapp.utils.DialogUtils;
import com.kkd.kkdapp.utils.EmailUtils;
import com.kkd.kkdapp.utils.IntentConstants;
import com.kkd.kkdapp.utils.LogUtil;
import com.kkd.kkdapp.utils.PreferenceUtils;
import com.kkd.kkdapp.utils.SystemUtils;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.AdapterView.OnItemClickListener;

/***
 * 
 * @Data 2016-03-11
 * 
 * @author mty
 * 
 * @Name 意见反馈
 * 
 */
public class FeedbackActivity extends BaseActivity implements OnClickListener {

	private static final int SEND_EMAIL = 0;
	private RelativeLayout top_img; // 返回
	private GridView mGridView;
	public static List<ImageItem> mDataList = new ArrayList<ImageItem>();
	private ImagePublishAdapter mAdapter;
	private Button submit_bt;
	private EditText content_ed; // 文本内容
	private Dialog toLoadDialog;
	private Thread sentThread;
	private Dialog mDialog;
	private PopupWindows mPopupWindows;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		mDataList.clear();
		setContentView(R.layout.activity_feedback);
		initView();
		initData();
		setListener();
	}

	/**************
	 * 初始化控件
	 **************/
	public void initView() {
		top_img = (RelativeLayout) this.findViewById(R.id.top_img);
		mGridView = (GridView) findViewById(R.id.gridview);
		content_ed = (EditText) this.findViewById(R.id.content_ed);
		submit_bt = (Button) this.findViewById(R.id.submit_bt);
		Button phone_bt = (Button) this.findViewById(R.id.phone_bt);
		phone_bt.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				SystemUtils.onEvent("Account_Sett_FeedBack_400TEL", 1);
				showDialog("拨打客服电话：4000-137-000");
			}
		});
		mGridView.setSelector(new ColorDrawable(Color.TRANSPARENT));
		mAdapter = new ImagePublishAdapter(this, mDataList);
		mGridView.setAdapter(mAdapter);
		mGridView.setOnItemClickListener(new OnItemClickListener() {
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				if (position == getDataSize()) {
					if (mPopupWindows != null)
						mPopupWindows = null;
					mPopupWindows = new PopupWindows(FeedbackActivity.this,
							mGridView);
					SystemUtils.hideKeyBoard(FeedbackActivity.this);
				} else {
					Intent intent = new Intent(FeedbackActivity.this,
							ImageZoomActivity.class);
					intent.putExtra(IntentConstants.EXTRA_IMAGE_LIST,
							(Serializable) mDataList);
					intent.putExtra(IntentConstants.EXTRA_CURRENT_IMG_POSITION,
							position);
					startActivityForResult(intent, 50);
				}
			}
		});

	}

	public void showDialog(String message) {

		if (mDialog != null) {
			mDialog.cancel();
			mDialog = null;
		}
		mDialog = DialogUtils.deleteBankDialog(this, message,
				new OnClickListener() {

					@Override
					public void onClick(View v) {
						switch (v.getId()) {
						case R.id.confirm_deletebank:

							Intent intent = new Intent(Intent.ACTION_CALL, Uri
									.parse("tel:4000137000"));
							startActivity(intent);
							break;
						case R.id.cancel_deletebank:
							mDialog.dismiss();
							break;
						}
					}
				});
		mDialog.show();

	}

	@Override
	protected void onResume() {
		super.onResume();
		notifyDataChanged(); // 当在ImageZoomActivity中删除图片时，返回这里需要刷新
	}

	@Override
	protected void onPause() {
		super.onPause();
		saveTempToPref();
		getTempFromPref();
	}

	private void notifyDataChanged() {
		mAdapter.notifyDataSetChanged();
	}

	@Override
	public void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		saveTempToPref();
	}

	/**************
	 * 注册监听事件
	 **************/
	public void setListener() {
		top_img.setOnClickListener(this);
		submit_bt.setOnClickListener(this);

	}

	private int getDataSize() {
		return mDataList == null ? 0 : mDataList.size();
	}

	public class PopupWindows extends PopupWindow {

		public PopupWindows(Context mContext, View parent) {

			View view = View.inflate(mContext, R.layout.item_popupwindow, null);
			view.startAnimation(AnimationUtils.loadAnimation(mContext,
					R.anim.fade_ins));
			LinearLayout ll_popup = (LinearLayout) view
					.findViewById(R.id.ll_popup);
			ll_popup.startAnimation(AnimationUtils.loadAnimation(mContext,
					R.anim.push_bottom_in_2));

			setWidth(LayoutParams.MATCH_PARENT);
			setHeight(LayoutParams.MATCH_PARENT);
			setFocusable(true);
			setOutsideTouchable(true);
			setContentView(view);
			showAtLocation(parent, Gravity.BOTTOM, 0, 0);
			update();

			Button bt2 = (Button) view
					.findViewById(R.id.item_popupwindows_Photo);
			Button bt3 = (Button) view
					.findViewById(R.id.item_popupwindows_cancel);
			bt2.setOnClickListener(new OnClickListener() {
				public void onClick(View v) {
					Intent intent = new Intent(FeedbackActivity.this,
							ImageBucketChooseActivity.class);
					intent.putExtra(IntentConstants.EXTRA_CAN_ADD_IMAGE_SIZE,
							getAvailableSize());
					startActivityForResult(intent, 50);
					dismiss();
				}
			});
			bt3.setOnClickListener(new OnClickListener() {
				public void onClick(View v) {
					dismiss();
				}
			});
			RelativeLayout close = (RelativeLayout) view
					.findViewById(R.id.close);
			close.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					dismiss();
				}
			});

		}
	}

	private static final int TAKE_PICTURE = 0x000000;
	private String path = "";

	private int getAvailableSize() {
		int availSize = CustomConstants.MAX_IMAGE_SIZE - mDataList.size();
		if (availSize >= 0) {
			return availSize;
		}
		return 0;
	}

	public String getString(String s) {
		String path = null;
		if (s == null)
			return "";
		for (int i = s.length() - 1; i > 0; i++) {
			s.charAt(i);
		}
		return path;
	}

	private void getTempFromPref() {
		SharedPreferences sp = getSharedPreferences(
				CustomConstants.APPLICATION_NAME, MODE_PRIVATE);
		String prefStr = sp.getString(CustomConstants.PREF_TEMP_IMAGES, null);
		if (!TextUtils.isEmpty(prefStr)) {
			Gson gson = new Gson();
			List<ImageItem> tempImages = gson.fromJson(prefStr,
					new TypeToken<List<ImageItem>>() {
					}.getType());
			mDataList = tempImages;
		}
	}

	private void removeTempFromPref() {
		SharedPreferences sp = getSharedPreferences(
				CustomConstants.APPLICATION_NAME, MODE_PRIVATE);
		sp.edit().remove(CustomConstants.PREF_TEMP_IMAGES).commit();
	}

	@SuppressWarnings("unchecked")
	private void initData() {
		// List<ImageItem> incomingDataList = (List<ImageItem>) getIntent()
		// .getSerializableExtra(IntentConstants.EXTRA_IMAGE_LIST);
		// if (incomingDataList != null) {
		// mDataList.addAll(incomingDataList);
		// }
	}

	private void saveTempToPref() {
		SharedPreferences sp = getSharedPreferences(
				CustomConstants.APPLICATION_NAME, MODE_PRIVATE);
		Gson gson = new Gson();
		String prefStr = gson.toJson(mDataList);
		sp.edit().putString(CustomConstants.PREF_TEMP_IMAGES, prefStr).commit();

	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.top_img:
			finish();
			removeTempFromPref();
			break;
		case R.id.submit_bt:
			SystemUtils.onEvent("Account_Sett_FeedBack_Submit", 1);
			if (!TextUtils.isEmpty(content_ed.getText().toString())) {
				ArrayList<String> paths = new ArrayList<String>();
				for (ImageItem i : mDataList) {
					paths.add(i.sourcePath);
				}
				try {
					String content = content_ed.getText().toString();
					if (content.length() <= 1000) {
						if (AppUtil.isConnect(BaseApplication.getInstance())) {
							EmailUtils
							.sendEmail(
									"用户"
											+ PreferenceUtils
													.getInstance()
													.getPhone(
															FeedbackActivity.this)
											+ "的反馈邮件",
									content_ed.getText().toString()
											+ "\n"
											+ PreferenceUtils
													.getInstance()
													.getcustomerId(
															FeedbackActivity.this)
													.split("&")[0]
											+ "\n"
											+ PreferenceUtils
													.getInstance()
													.getcustomerId(
															FeedbackActivity.this)
													.split("&")[1], paths);
							showToast("反馈成功", new onToastDismiss() {

								@Override
								public void onToastDismiss() {
									finish();
								}
							});
						}else{
							showToast("没有网络无法提交");
						}
						
					} else {
						showToast("反馈内容不能超过1000字");
					}

				} catch (Exception e) {
					// 忽略
				}

				
			} else {
				showToast("写些意见反馈吧，被采纳会获得奖励哦~");
			}
			break;
		}

	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			finish();
			removeTempFromPref();
		}
		return super.onKeyDown(keyCode, event);
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		switch (requestCode) {
		case TAKE_PICTURE:
			if (mDataList.size() < CustomConstants.MAX_IMAGE_SIZE
					&& resultCode == -1 && !TextUtils.isEmpty(path)) {
				ImageItem item = new ImageItem();
				item.sourcePath = path;
				mDataList.add(item);
			}
			break;
		}
		if (resultCode == 100) {
			List<ImageItem> incomingDataList = (List<ImageItem>) data
					.getSerializableExtra(IntentConstants.EXTRA_IMAGE_LIST);
			if (incomingDataList != null) {
				mDataList.addAll(incomingDataList);
				mAdapter = new ImagePublishAdapter(this, mDataList);
				mGridView.setAdapter(mAdapter);
				notifyDataChanged();
				for (int i = 0; i < incomingDataList.size(); i++) {
					LogUtil.e("imageId", incomingDataList.get(i).imageId);
					LogUtil.e("thumbnailPath",
							incomingDataList.get(i).thumbnailPath);
					LogUtil.e("sourcePath", incomingDataList.get(i).sourcePath);
				}
			}
		}
		if (resultCode == 200) {
			mAdapter = new ImagePublishAdapter(this, mDataList);
			mGridView.setAdapter(mAdapter);
			notifyDataChanged();
		}
	}

	@Override
	protected void onDestroy() {
		closeToLoadDialog();
		super.onDestroy();
	}

	public void showToLoadDialog(String content) {
		if (toLoadDialog != null) {
			toLoadDialog.cancel();
			toLoadDialog = null;
		}
		toLoadDialog = DialogUtils.toLoadDialog(this, content);
		toLoadDialog.show();
	}

	public void closeToLoadDialog() {
		if (toLoadDialog != null) {
			toLoadDialog.dismiss();
			toLoadDialog.cancel();
			toLoadDialog = null;
		}
	}

}
